//
//  SPPayService.m
//  BaseProject
//
//  Created by Sailer Guo on 2019/12/25.
//  Copyright © 2019 Beijing Shopin Retail Development Co., Ltd. All rights reserved.
//

#import "SPPayService.h"
#import "HTTPService+SPOrder.h"
#import "Environment.h"
#import <AlipaySDK/AlipaySDK.h>
#import <WechatOpenSDK/WechatAuthSDK.h>
#import <WXApi.h>


NSString *const kAlipayResultNotification = @"alipayPayResult";
NSString *const kWechatPaySuccessNotification = @"weChatPaySuccess";
NSString *const kWechatPayFailureNotification = @"weChatPayfailure";

@implementation SPPayService


- (RACSignal *)payServiceForOrderNo:(NSString *)orderNo payType:(SPPayType)type {

    RACSignal *paySignal = [[[Environment sharedInstance].apiService getSignData:orderNo payType:type] flattenMap:^__kindof RACSignal * _Nullable(id  _Nullable value) {
        return [self invokePayService:type signData:value];
    }];
    return paySignal;
}

- (RACSignal *)invokePayService:(SPPayType)payType signData:(NSDictionary *)signData{
    RACSignal *paySignal = nil;
    
    if (payType == SPPayTypeAliPay) {
        NSString *alipayQuickSignData = signData[@"sign"];
        NSString *appScheme = @"alipayshangpin";
        
        @weakify(self)
        RACSignal *aliCallbackSignal = [RACSignal createSignal:^RACDisposable * _Nullable(id<RACSubscriber>  _Nonnull subscriber) {
            
            @strongify(self)
            [[AlipaySDK defaultService] payOrder:alipayQuickSignData fromScheme:appScheme callback:^(NSDictionary *resultDic) {
                
                [self sloveAlipayResult:resultDic subscriber:subscriber];
            }];
            
            return [RACDisposable disposableWithBlock:^{
                
            }];
        }];
        
        RACSignal *aliNotiSignal = [[[NSNotificationCenter defaultCenter] rac_addObserverForName:kAlipayResultNotification object:nil] flattenMap:^__kindof RACSignal * _Nullable(NSNotification * _Nullable value) {
            NSDictionary *resultDict = value.object;
            
            return [RACSignal createSignal:^RACDisposable * _Nullable(id<RACSubscriber>  _Nonnull subscriber) {
                [self sloveAlipayResult:resultDict subscriber:subscriber];
                return [RACDisposable disposableWithBlock:^{
                    
                }];
            }];
        }];

        paySignal = [RACSignal merge:@[aliCallbackSignal,aliNotiSignal]];
        
    } else {
        
        if (![WXApi isWXAppInstalled]) {
            paySignal = [RACSignal createSignal:^RACDisposable * _Nullable(id<RACSubscriber>  _Nonnull subscriber) {
               BOOL payResult = NO;
                NSString *memo = @"请安装微信客户端";
                RACTuple *tuple = RACTuplePack(@(payResult),memo,@(SPPayTypeWechat));
                
                NSError *error = [NSError errorWithDomain:RACSignalErrorDomain code:1000 userInfo:@{@"error":tuple}];
                [subscriber sendError:error];
                
            return [RACDisposable disposableWithBlock:^{
                               
                }];
            }];
            
            return paySignal;
        }
        
        PayReq *request = [[PayReq alloc]init];
        //微信openID 唯一
        request.openID  = @"xxxxx";
        //商家向财付通申请的商家id
        request.partnerId = signData[@"partnerid"];
        ///** 预支付订单 */
        request.prepayId = signData[@"prepayid"];
        ///** 商家根据财付通文档填写的数据和签名 */
        request.package = signData[@"package"] ;
        //** 随机串，防重发 */
        request.nonceStr = signData[@"noncestr"];
        ///** 时间戳，防重发 */
        NSString *timeStr = signData[@"timestamp"] ;
        request.timeStamp = timeStr.intValue;
        //** 商家根据微信开放平台文档对数据做的签名 */
        request.sign = signData[@"sign"];
        //发送请求到微信，等待微信返回onResp
        [WXApi sendReq:request completion:NULL];
        
        RACSignal *successSignal = [[[NSNotificationCenter defaultCenter] rac_addObserverForName:kWechatPaySuccessNotification object:nil] flattenMap:^__kindof RACSignal * _Nullable(NSNotification * _Nullable value) {
            return [RACSignal createSignal:^RACDisposable * _Nullable(id<RACSubscriber>  _Nonnull subscriber) {
               
                BOOL payResult = NO;
                NSString *memo;
                RACTuple *tuple = RACTuplePack(@(payResult),memo,@(SPPayTypeWechat));
                [subscriber sendNext:tuple];
                [subscriber sendCompleted];
                return [RACDisposable disposableWithBlock:^{
                    
                }];
            }];
        }];
        
        RACSignal *errorSignal = [[[NSNotificationCenter defaultCenter] rac_addObserverForName:kWechatPayFailureNotification object:nil] flattenMap:^__kindof RACSignal * _Nullable(NSNotification * _Nullable value) {
            
            return [RACSignal createSignal:^RACDisposable * _Nullable(id<RACSubscriber>  _Nonnull subscriber) {
                
                BOOL payResult = NO;
                NSString *memo;
                RACTuple *tuple = RACTuplePack(@(payResult),memo,@(SPPayTypeWechat));
                
                NSError *error = [NSError errorWithDomain:RACSignalErrorDomain code:1000 userInfo:@{@"error":tuple}];
                [subscriber sendError:error];
                
                return [RACDisposable disposableWithBlock:^{
                    
                }];
            }];
        }];
        
        paySignal = [RACSignal merge:@[successSignal,errorSignal]];
    }
    
    return paySignal;
}

- (RACSignal *)checkOrder:(NSString *)orderNo payType:(SPPayType)type {
    return [[Environment sharedInstance].apiService checkOrder:orderNo payType:type];
}

- (void)sloveAlipayResult:(NSDictionary *)resultDic subscriber:(id<RACSubscriber>)subscriber {
    
    if ([resultDic[@"resultStatus"] integerValue] == 9000) {
        NSLog(@"result %@",resultDic);
        BOOL payResult = YES;
        NSString *memo = resultDic[@"memo"];
        
        RACTuple *payResultTuple = RACTuplePack(@(payResult),memo,@(SPPayTypeAliPay));
        [subscriber sendNext:payResultTuple];
        [subscriber sendCompleted];
        
    } else {
        NSLog(@"result %@",resultDic);
        BOOL payResult = NO;
        NSString *memo = resultDic[@"memo"];
        
        RACTuple *payResultTuple = RACTuplePack(@(payResult),memo,@(SPPayTypeAliPay));

        NSError *error = [NSError errorWithDomain:RACSignalErrorDomain code:1000 userInfo:@{@"error":payResultTuple}];
        [subscriber sendError:error];
    }
}

- (void)switchEnv:(EnvironmentType)env {
    NSLog(@"支付依赖于HTTP Service,HTTP Service 切换了环境支付也就切换了");
}

@end
